package com.situ.mall.manager.service.impl;

import com.situ.mall.manager.entity.Admin;
import com.situ.mall.manager.mapper.AdminMapper;
import com.situ.mall.manager.service.AdminService;
import com.situ.mall.manager.util.MD5Util;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@AllArgsConstructor //根据当前类的所有属性构造全参的构造方法
public class AdminServiceImpl implements AdminService {

    /*
    新的注解方式 构造方法的自动注入 不用resource和autowired
    spring4.X支持构造方法注入 推荐使用构造方法注入
    提供一个有参构造方法，不需要依赖于任何注解
     */
    private AdminMapper adminMapper;

//    //有参构造方法
//    public AdminServiceImpl(AdminMapper adminMapper){
//        this.adminMapper = adminMapper;
//    }

    @Override
    public Admin login(Admin admin) throws Exception {
        //验证参数
        if(admin.getUsername() == null ||
                admin.getUsername().length() < 3 ||
                admin.getUsername().length() > 16){
            throw new Exception("用户名必须是3-16位的字符串");
        }
        if(admin.getPassword() == null ||
                admin.getPassword().length() < 3 ||
                admin.getPassword().length() > 16){
            throw new Exception("密码必须是3-16位的字符串");
        }

        //逻辑处理
        //访问数据库
        Admin sAdmin = adminMapper.selectByUsername(admin.getUsername());
        if(sAdmin == null){
            throw new Exception("用户名不存在");
        }
        //验证密码
        String password = admin.getPassword();  //用户输入的密码
        password = MD5Util.getMD5(password + sAdmin.getSalt());
        System.out.println(password);
        if(! password.equals(sAdmin.getPassword())){
            throw new Exception("密码错误");
        }
        //用户状态
        if(sAdmin.getStatus() == 1){
            throw new Exception("用户被禁用");
        }

        return sAdmin;  //返回一系列信息
    }

    @Override
    public Admin modifyPwd(Integer id, String oldPassword, String newPassword,
                           String rePassword) throws Exception {
        if(oldPassword == null ||
                oldPassword.length() < 3 ||
                oldPassword.length() > 16){
            throw new Exception("旧密码格式不正确");
        }
        if(newPassword == null ||
                newPassword.length() < 3 ||
                newPassword.length() > 16){
            throw new Exception("新密码格式不正确");
        }
        if(! newPassword.equals(rePassword)){
            throw new Exception("两次密码不一致");
        }

        Admin admin = adminMapper.selectById(id);
        String md5Pwd = MD5Util.getMD5(oldPassword + admin.getSalt());
        if(! md5Pwd.equals(admin.getPassword())){
            throw new Exception("旧密码不正确");
        }
        admin.setPassword(MD5Util.getMD5(newPassword + admin.getSalt()));
        adminMapper.update(admin);
        return admin;
    }

    @Override
    public Admin edit(Admin admin) throws Exception {
        return null;
    }
}
